#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRBuilder.h"
#include "Module.h"
#include "Type.h"
 
#include <iostream>
#include <memory>
 
#ifdef DEBUG  // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项
#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl;  // 输出行号的简单示例
#else
#define DEBUG_OUTPUT
#endif
 
#define CONST_INT(num) \
    ConstantInt::get(num, module)
 
#define CONST_FP(num) \
    ConstantFP::get(num, module) // 得到常数值的表示,方便后面多次用到
    
int main() {
  auto module = new Module("if code");
  auto builder = new IRBuilder(nullptr, module); //该类提供了独立的接口创建各种 IR 指令
  Type *Int32Type = Type::get_int32_type(module);
  Type *FloatType = Type::get_float_type(module);
  
  // main函数
  auto mainFun = Function::create(FunctionType::get(Int32Type, {}),"main", module);
  auto bb = BasicBlock::create(module, "entry", mainFun); //创建BasicBlock
  builder->set_insert_point(bb);  //将当前插入指令点的位置设在bb
  
  auto aAlloca=builder->create_alloca(FloatType); //float a
  builder->create_store(CONST_FP(5.555), aAlloca);  //a = 5.555;
  auto aLoad = builder->create_load(aAlloca);  //a
  
  auto cmp = builder->create_fcmp_gt(aLoad, CONST_FP(1.000));  //if(a > 1)
  auto trueBB = BasicBlock::create(module, "truebb", mainFun);    // true
  auto falseBB = BasicBlock::create(module, "falsebb", mainFun);  // false
  auto br = builder->create_cond_br(cmp, trueBB, falseBB);  // if(a > 1)goto true else goto false
  
  builder->set_insert_point(trueBB);  // if true; 分支的开始需要SetInsertPoint设置
  builder->set_insert_point(trueBB);
  builder->create_ret(CONST_INT(233));
  builder->set_insert_point(falseBB);
  builder->create_ret(CONST_INT(0));
 
  std::cout << module->print();
  delete module;
  return 0;
}